package cn.edu.scau.cmi.ema.controller.rest;

import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.io.IOException;

import com.google.gson.Gson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import cn.edu.scau.cmi.ema.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiPsonService;
import cn.edu.scau.cmi.ema.base.CmiEmaController;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.service.*;

import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.WebDataBinder;

@Controller("StandardRestController")
public class StandardRestController extends CmiEmaController {

	/**
	 * Create a new Standard entity
	 * 
	 */
	@RequestMapping(value = "/newStandard", method = RequestMethod.POST)
	@ResponseBody
	public Object newStandard(@RequestBody Standard standard) {
		standardService.saveStandard(standard);
		return JSONObject.parse(cmiPsonService.toJsonString(standardDAO.findStandardByPrimaryKey(standard.getId()), 2));
	}

	@RequestMapping(value = "/restNewStandard", method = RequestMethod.POST)
	@ResponseBody
	public Object restNewStandard(@RequestBody String standardJson) {
		Standard standard = new Gson().fromJson(standardJson, Standard.class);
		appendReferences(standard);
		standardService.saveStandard(standard);
		return JSONObject.parse(cmiPsonService.toJsonString(standardDAO.findStandardByPrimaryKey(standard.getId()), 2));
	}

	@RequestMapping(value = "/saveStandard", method = RequestMethod.PUT)
	@ResponseBody
	public Standard saveStandard(@RequestBody Standard standard) {
		standardService.saveStandard(standard);
		return standardDAO.findStandardByPrimaryKey(standard.getId());
	}

	@RequestMapping(value = "/restSaveStandard", method = RequestMethod.PUT)
	@ResponseBody
	public Object restSaveStandard(@RequestBody String standardJson) {
		Standard standard = new Gson().fromJson(standardJson, Standard.class);
		appendReferences(standard);
		CmiPsonService cmiPsonService = new CmiPsonService();
		standardService.saveStandard(standard);
		return JSONObject.parse(cmiPsonService.toJsonString(standardDAO.findStandardByPrimaryKey(standard.getId()), 1));
	}

	@RequestMapping(value = "/restDeleteStandard/{standardId}", method = RequestMethod.DELETE)
	@ResponseBody
	public void restDeleteStandard(@PathVariable Integer standardId) {
		Standard standard = standardDAO.findStandardByPrimaryKey(standardId);
		standardService.deleteStandard(standard);
	}

	@RequestMapping(value = "/restConfirmDeleteStandards")
	@ResponseBody
	public Object restConfirmDeleteStandards(@RequestBody Set<Integer> deleteStandardsIds) {
		Set<Standard> deleteStandards = standardDAO.findStandardsByIds(deleteStandardsIds);
		Set<Standard> referencedStandards = standardService.loadReferenceStandards(deleteStandards);
		deleteStandards.removeAll(referencedStandards);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("referencedEntitys", referencedStandards);
		jsonObject.put("deleteEntitys", deleteStandards);
		return JSONObject.parse(jsonObject.toJSONString());
	}

	@RequestMapping("/restDeleteStandards")
	@ResponseBody
	public Object restDeleteStandards(@RequestBody Set<Standard> deleteStandards) {
		Iterator<Standard> iterator = deleteStandards.iterator();
		while (iterator.hasNext()) {
			Standard currentStandard = iterator.next();
			standardService.deleteStandard(currentStandard);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("url", "listStandards");
		return JSONObject.parse(jsonObject.toJSONString());
	}
	// loadself

	@RequestMapping(value = "/restLoadStandard/{standardId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadStandard(@PathVariable Integer standardId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject
				.parse(cmiPsonService.toPsonString(standardDAO.findStandardByPrimaryKey(standardId), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadStandardStandard/{standardId}/standard", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadStandardStandard(@PathVariable Integer standardId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(standardDAO.findStandardByPrimaryKey(standardId).getReplacedstandard(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadStandardStandardtype/{standardId}/standardtype", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadStandardStandardtype(@PathVariable Integer standardId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(standardDAO.findStandardByPrimaryKey(standardId).getStandardtype(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadStandardStandardlevel/{standardId}/standardlevel", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadStandardStandardlevel(@PathVariable Integer standardId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(standardDAO.findStandardByPrimaryKey(standardId).getStandardlevel(), 2, cmiPagination));
	}
	// loadReferenceds
	// TODO loadReferencedsPson，这个方法有一些问题，待修复

	@RequestMapping(value = "/restLoadStandardFeaturestandards/{standardId}/featurestandards/{relatedfeaturestandardId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadStandardFeaturestandards(@PathVariable Integer standardId,
			@PathVariable Integer relatedfeaturestandardId, @RequestBody CmiPagination cmiPagination) {
		Featurestandard featurestandard = featurestandardDAO.findFeaturestandardByPrimaryKey(relatedfeaturestandardId,
				-1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(featurestandard, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadStandardFoodtypes/{standardId}/foodtypes/{relatedfoodtypeId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadStandardFoodtypes(@PathVariable Integer standardId, @PathVariable Integer relatedfoodtypeId,
			@RequestBody CmiPagination cmiPagination) {
		Foodtype foodtype = foodtypeDAO.findFoodtypeByPrimaryKey(relatedfoodtypeId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(foodtype, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadStandardStandards/{standardId}/standards/{relatedstandardId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadStandardStandards(@PathVariable Integer standardId, @PathVariable Integer relatedstandardId,
			@RequestBody CmiPagination cmiPagination) {
		Standard standard = standardDAO.findStandardByPrimaryKey(relatedstandardId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(standard, 2, cmiPagination));
	}

	public void appendReferences(Standard standard) {

		Standard replacedstandard = standard.getReplacedstandard();
		if (replacedstandard != null)
			standard.setReplacedstandard(standardService.findStandardByPrimaryKey(replacedstandard.getId()));

		Standardtype standardtype = standard.getStandardtype();
		if (standardtype != null)
			standard.setStandardtype(standardtypeService.findStandardtypeByPrimaryKey(standardtype.getId()));

		Standardlevel standardlevel = standard.getStandardlevel();
		if (standardlevel != null)
			standard.setStandardlevel(standardlevelService.findStandardlevelByPrimaryKey(standardlevel.getId()));

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Featurestandard> featurestandardsForStandard = new HashSet<>();
		for (Featurestandard featurestandard_Standard : standard.getFeaturestandardsForStandard()) {
			featurestandardsForStandard
					.add(featurestandardService.findFeaturestandardByPrimaryKey(featurestandard_Standard.getId()));
		}
		standard.setFeaturestandardsForStandard(featurestandardsForStandard);

		// 引用表是纯联系表的情况
		Set<Foodtype> foodtypesForStandard = new HashSet<>();
		for (Foodtype foodtypeForStandard : standard.getFoodtypesForStandard()) {
			foodtypesForStandard.add(foodtypeService.findFoodtypeByPrimaryKey(foodtypeForStandard.getId()));
		}
		standard.setFoodtypesForStandard(foodtypesForStandard);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Standard> standardsForReplacedstandard = new HashSet<>();
		for (Standard standard_Replacedstandard : standard.getStandardsForReplacedstandard()) {
			standardsForReplacedstandard
					.add(standardService.findStandardByPrimaryKey(standard_Replacedstandard.getId()));
		}
		standard.setStandardsForReplacedstandard(standardsForReplacedstandard);
	}

	@RequestMapping(value = "/restGetStandardStandard/{standardId}/standard", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetStandardStandard(@PathVariable Integer standardId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(standardDAO.findStandardByPrimaryKey(standardId).getReplacedstandard(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetStandardStandardtype/{standardId}/standardtype", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetStandardStandardtype(@PathVariable Integer standardId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(standardDAO.findStandardByPrimaryKey(standardId).getStandardtype(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetStandardStandardlevel/{standardId}/standardlevel", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetStandardStandardlevel(@PathVariable Integer standardId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(standardDAO.findStandardByPrimaryKey(standardId).getStandardlevel(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetStandardFeaturestandards/{standardId}/featurestandards", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetStandardFeaturestandards(@PathVariable Integer standardId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				standardDAO.findStandardByPrimaryKey(standardId).getFeaturestandardsForStandard(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetStandardFoodtypes/{standardId}/foodtypes", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetStandardFoodtypes(@PathVariable Integer standardId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(standardDAO.findStandardByPrimaryKey(standardId).getFoodtypesForStandard(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetStandardStandards/{standardId}/standards", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetStandardStandards(@PathVariable Integer standardId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				standardDAO.findStandardByPrimaryKey(standardId).getStandardsForReplacedstandard(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restListStandards", method = RequestMethod.GET)
	@ResponseBody
	public Object restListStandards() {
		return JSONObject.parse(cmiPsonService.toJsonString(standardService.loadStandards(), 2));
	}

	@RequestMapping(value = "/restListStandardsPost", method = RequestMethod.POST)
	@ResponseBody
	public Object restListStandardsPost(@RequestBody CmiPagination cmiPagination) {

		CmiPsonService cmiPsonService = new CmiPsonService();
		cmiPagination = standardPaginationService.updateAppPagination(cmiPagination);
		int startResult = (cmiPagination.getCurrentPagination() - 1) * cmiPagination.getPaginationSize();

		Set<Standard> standards = standardDAO.findAllStandards(startResult, cmiPagination.getPaginationSize());
		String standardString = cmiPsonService.toPsonString(standards, 2, cmiPagination);

		return JSONObject.parse(standardString);
	}

	@RequestMapping("/standardSelectBox")
	@ResponseBody
	public JSONObject standardSelectBox(@RequestParam(required = false) String searchTable,
			@RequestParam(required = false) Set<Integer> searchValue, // 杨宏宇2019-9-10：searchValue是在selectpage.js的616行定义，如果要修改searchValue的名称，1.可以修改在selectpage.js修改；2.可以
																		// @RequestParam(value="searchValue", required =
																		// false) Set<Integer> someName
			@RequestParam(required = false, defaultValue = "10") int paginationSize,
			@RequestParam(required = false, defaultValue = "1") int pageNumber,
			@RequestParam(value = "qWord[]", required = false) String queryword,
			@RequestParam(required = false) String selectItem) throws IOException {
		Set entitySet = null;
		Integer count = 0;

		// 初始化原始值

		if (searchValue != null) {
			switch (searchTable) {
			// 外键
			case "Standardtype":
				entitySet = standardtypeService.loadStandardtypesByIdSet(searchValue);
				break;
			case "Standardlevel":
				entitySet = standardlevelService.loadStandardlevelsByIdSet(searchValue);
				break;

			// 被引用键
			case "Featurestandard":
				entitySet = featurestandardService.loadFeaturestandardsByIdSet(searchValue);
				break;

			case "Foodtype":
				entitySet = foodtypeService.loadFoodtypesByIdSet(searchValue);
				break;
			case "Standard":
				entitySet = standardService.loadStandardsByIdSet(searchValue);
				break;
			}
			// 没有测试，深度需要多少？？？
			String jsonData = cmiPsonService.toJsonString(entitySet, 1);
			JSONArray jsonArray = new JSONArray();
			jsonArray = (JSONArray) JSON.parse((String) jsonData);

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("list", jsonArray);
			jsonObject.put("totalRow", entitySet.size());
			return jsonObject;
		}

		// 不根据关键字进行搜索
		if (queryword == null || queryword.trim() == "") {
			switch (selectItem) {
			// 外键
			case "Standardtype":
				entitySet = standardtypeDAO.findAllStandardtypes((pageNumber - 1) * paginationSize, paginationSize);
				count = standardtypeService.countStandardtypes();
				break;
			case "Standardlevel":
				entitySet = standardlevelDAO.findAllStandardlevels((pageNumber - 1) * paginationSize, paginationSize);
				count = standardlevelService.countStandardlevels();
				break;

			// 被引用键
			case "Featurestandard":
				entitySet = featurestandardDAO.findAllFeaturestandards((pageNumber - 1) * paginationSize,
						paginationSize);
				count = featurestandardService.countFeaturestandards();
				break;

			case "Foodtype":
				entitySet = foodtypeDAO.findAllFoodtypes((pageNumber - 1) * paginationSize, paginationSize);
				count = foodtypeService.countFoodtypes();
				break;
			case "Standard":
				entitySet = standardDAO.findAllStandards((pageNumber - 1) * paginationSize, paginationSize);
				count = standardService.countStandards();
				break;
			}
		} else {
			switch (selectItem) {
			// 外键
			case "Standardtype":
				entitySet = standardtypeDAO.findStandardtypeByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = standardtypeService.countStandardtypesByName(queryword);
				break;
			case "Standardlevel":
				entitySet = standardlevelDAO.findStandardlevelByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = standardlevelService.countStandardlevelsByName(queryword);
				break;

			// 被引用键
			case "Featurestandard":
				entitySet = featurestandardDAO.findFeaturestandardByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = featurestandardService.countFeaturestandardsByName(queryword);
				break;

			case "Foodtype":
				entitySet = foodtypeDAO.findFoodtypeByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = foodtypeService.countFoodtypesByName(queryword);
				break;
			case "Standard":
				entitySet = standardDAO.findStandardByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = standardService.countStandardsByName(queryword);
				break;
			}
		}
		/**
		 * 将Json数据转换成jsonArray形式，需要通过pson方式进行转换，然后再转换成JsonArray。因为存在懒加载
		 * 没有直接使用CmiPsonService中的fromJson方法是因为，fromJson方法会将int类型的直接转换成double类型的数据，这个问题还没有解决
		 */
		// 没有测试，深度需要多少？？？
		String jsonData = cmiPsonService.toJsonString(entitySet, 1);
		JSONArray jsonArray = new JSONArray();
		jsonArray = (JSONArray) JSON.parse((String) jsonData);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("list", jsonArray);
		jsonObject.put("paginationSize", paginationSize);
		jsonObject.put("pageNumber", pageNumber);
		jsonObject.put("totalRow", count);
		jsonObject.put("totalPaginations",
				count % paginationSize == 0 ? count / paginationSize : count / paginationSize + 1);
		return jsonObject;
	}
}
